package com.weitu.permission.resource.controller;

import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.base.entity.JsonTreeData;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.resource.entity.Resource;
import com.weitu.permission.resource.service.ResourceService;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.util.TreeNodeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.util.SavedRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * Created by WT-SUN on 2017/3/14.
 */
@Controller
@RequestMapping(value = "permission/resource")
public class ResourceController extends BaseController {

    @Autowired
    private ResourceService resourceService;

    /**
     * 跳转至菜单页面
     *
     * @return
     */
    @RequestMapping(value = "/list")
    public String list() {
        return BASE_JSP_PATH + "permission/resource/list";
    }

    /**
     * 跳转至菜单添加页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("toAddResourcesPage")
    public String toAddResourcesPage(ModelMap modelMap) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        modelMap.addAllAttributes(paramMap);
        return BASE_JSP_PATH + "permission/resource/add";
    }

    /**
     * 跳转至菜单编辑页面
     *
     * @param id
     * @return
     */
    @RequestMapping("toEditResourcesPage")
    public ModelAndView toEditResourcesPage(String id) {
        ModelAndView modelAndView = new ModelAndView();
        Resource resource = resourceService.selectById(id);
        modelAndView.addObject("resource", resource);
        modelAndView.setViewName(BASE_JSP_PATH + "permission/resource/edit");
        return modelAndView;
    }

    /**
     * 查询菜单树数据
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectByPrimaryKey")
    public List<JsonTreeData> selectByPrimaryKey(String id) {
        List<Map> resources = resourceService.selectByPrimaryKey(id);
        List<JsonTreeData> treeDataList = new ArrayList<JsonTreeData>();
        for (Map<String, String> map : resources) {
            JsonTreeData treeData = new JsonTreeData();
            treeData.setId(map.get("id"));
            treeData.setPid(map.get("parentId"));
            treeData.setText(map.get("name"));
            treeDataList.add(treeData);
        }
        List<JsonTreeData> newTreeDataList = TreeNodeUtil.getFatherNode(treeDataList);
        JsonTreeData jsonTreeData = new JsonTreeData();
        jsonTreeData.setId("0");
        jsonTreeData.setText("顶级目录");
        jsonTreeData.setState("open");
        jsonTreeData.setChildren(newTreeDataList);
        List<JsonTreeData> jsonTreeDataList = new ArrayList<JsonTreeData>();
        jsonTreeDataList.add(jsonTreeData);
        return jsonTreeDataList;
    }

    /**
     * 添加菜单
     *
     * @param resource
     * @return
     */
    @ResponseBody
    @RequestMapping("insertSelective")
    @Transactional(readOnly = false)//需要事务操作必须加入此注解
    @SystemLog(module = "菜单管理", methods = "添加菜单")
    public AjaxResult insertSelective(Resource resource) {
        String id = IDGenerator.getId();
        resource.setId(id);
        resource.setDelState(0);
        String time = DateTimeUtil.formatterDateTime();
        resource.setAddTime(time);
        int boo = resourceService.insertSelective(resource);
        if (boo == 1) {
            return success("添加成功");
        } else {
            return fail("添加失败");
        }
    }

    /**
     * 删除菜单项
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteByPrimaryKey")
    @Transactional(readOnly = false)
    @SystemLog(module = "菜单管理", methods = "删除菜单")
    public AjaxResult deleteByPrimaryKey(String id) {
        int boo = resourceService.deleteByPrimaryKey(id);
        if (boo >= 1) {
            return success("删除成功");
        } else {
            return fail("删除失败");
        }
    }

    /**
     * 更新菜单
     *
     * @param resource
     * @return
     */
    @ResponseBody
    @RequestMapping("updateByPrimaryKeySelective")
    @Transactional(readOnly = false)
    @SystemLog(module = "菜单管理", methods = "更新菜单")
    public AjaxResult updateByPrimaryKeySelective(Resource resource) {
        String time = DateTimeUtil.formatterDateTime();
        resource.setUpdateTime(time);
        int boo = resourceService.updateByPrimaryKeySelective(resource);
        if (boo == 1) {
            return success("更新成功");
        } else {
            return fail("更新失败");
        }
    }

    /**
     * 加载菜单表格数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/treeTable", method = RequestMethod.POST)
    public Object treeTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);

        int totalNum = this.resourceService.queryTreeCount(paramMap);//获取列表总数量
        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<Resource> dataList = this.resourceService.queryTreeList(paramMap);//获取列表数据
        Object data = dataGridPagination.flushDataGridData(dataList);
        return data;
    }

    /**
     * 根据用户查询目录菜单
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectResourcesByUserId", method = RequestMethod.POST)
    public List<Map> selectResourcesByUserId(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();

        putParametersIntoMap(paramMap);
        User loginUser = getSessionUser();
        String name = loginUser.getName();
        String deptId = loginUser.getDepartment().getId();
        paramMap.put("name", name);
        paramMap.put("deptId", deptId);
        List<Map> resources = resourceService.selectResourcesByUserId(paramMap);
        return resources;
    }

    /**
     * 权限菜单
     *
     * @param authorityId
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectAllResourcesByAuthorityId")
    public List<JsonTreeData> selectAllResourcesByAuthorityId(String authorityId) {
        return resourceService.selectAllResourcesByAuthorityId(authorityId);
    }

    /**
     * 根据id查询菜单
     *
     * @param resourceId
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectAllResourcsById")
    public List<JsonTreeData> selectAllResourcsById(String resourceId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        User loginUser = getSessionUser();
        String name = loginUser.getName();
        String deptId = loginUser.getDepartment().getId();
        paramMap.put("id", resourceId);
        paramMap.put("name", name);
        paramMap.put("deptId", deptId);
        return resourceService.selectAllResourcsById(paramMap);
    }

    /**
     * 查询标识是否存在
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectByCode")
    public AjaxResult selectByCode(String code) {
        Resource resource = resourceService.selectByCode(code);
        if (null == resource) {
            return success("当前标识不存在");
        } else {
            return fail("当前标识已存在");
        }
    }

    @ResponseBody
    @RequestMapping("/selectIdByCode")
    public String selectIdByCode(String code){
        Resource resource = resourceService.selectByCode(code);
        String id="";
        if (resource!=null){
            id=resource.getId();
        }
        return id;
    }

    /**
     * 更新上级目录时查询目录
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectAllByUserId")
    public List<JsonTreeData> selectAllByUserId() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        User loginUser = getSessionUser();
        String name = loginUser.getName();
        String deptId = loginUser.getDepartment().getId();
        List<Map> resources = resourceService.selectAllByUserId(paramMap);
        List<JsonTreeData> treeDataList = new ArrayList<JsonTreeData>();
        for (Map<String, String> map : resources) {
            JsonTreeData treeData = new JsonTreeData();
            treeData.setId(map.get("id"));
            treeData.setPid(map.get("parentId"));
            treeData.setText(map.get("text"));
            treeDataList.add(treeData);
        }
        List<JsonTreeData> newTreeDataList = TreeNodeUtil.getFatherNode(treeDataList);
        JsonTreeData jsonTreeData = new JsonTreeData();
        jsonTreeData.setId("0");
        jsonTreeData.setText("顶级目录");
        jsonTreeData.setState("open");
        jsonTreeData.setChildren(newTreeDataList);
        List<JsonTreeData> jsonTreeDataList = new ArrayList<JsonTreeData>();
        jsonTreeDataList.add(jsonTreeData);
        return jsonTreeDataList;
    }
}


